package com.test45_JUC;

import java.util.concurrent.*;

/**
 * ThreadPoolExecutor，所有线程池的创建，都是由这个类的构造方法来创建的。
 * 在创建ThreadPoolExecutor类对象实例时，需要通过RejectedExecutionHandler接口配置拒绝策略，
 * 而所谓拒绝策略指的就是在线程池以及任务队列被占满时对于新任务的处理形式。
 */
public class Demo27_ThreadPoolExecutor {

    public static void main(String[] args) {
        // test1();
        test2();
    }

    /**
     * 调用者拒绝策略，ThreadPoolExecutor.CallerRunsPolicy
     * 在执行时如果发现线程池的资源不足了，那么最后就会由任务的发布线程来进行任务的处理执行。
     */
    public static void test1() {
        BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(1);
        ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 2, 1, TimeUnit.SECONDS, queue,
                Executors.defaultThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy());
        for (int x = 0; x < 5; x++) {
            final int temp = x;
            executor.submit(() -> {
                System.out.printf("【%s】处理YOOTK任务，x = %d%n",
                        Thread.currentThread().getName(), temp);
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        executor.shutdown();
    }

    /**
     * 直接中断拒绝策略，ThreadPoolExecutor.AbortPolicy（默认）
     * 如果线程池的资源已经满负荷了，那么最终就会直接产生RejectedExecutionException异常。
     */
    public static void test2() {
        BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(1);
        ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 2, 1, TimeUnit.SECONDS, queue,
                Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
        for (int x = 0; x < 5; x++) {
            final int temp = x;
            executor.submit(() -> {
                System.out.printf("【%s】处理YOOTK任务，x = %d%n",
                        Thread.currentThread().getName(), temp);
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        executor.shutdown();
    }
}
